
import { Component, OnInit, ViewChild } from '@angular/core';
//增删改查共通Service
import { CommService } from '../../comm/comm.service';
import { ReportUrls } from '../../comm/report.urls.conf';
import { SubArea } from '../../model/report/sub-area';
import { QueryModel } from '../../model/report/query-model';
import { DxDropDownBoxComponent } from 'devextreme-angular';
import { GlobalDataManager } from 'app/ptpmc/comm/global-data-manager';
import * as moment from 'moment';

@Component({
  selector: 'app-report-email-task-config',
  templateUrl: './email-task-config.component.html',
  styleUrls: ['./email-task-config.component.scss']
})

export class EmailTaskConfigComponent implements OnInit {
  title = '邮件定时任务配置';
  /*生产线*/
  public subAreaItems: SubArea[];
  public subAreaSelected: any[];
  @ViewChild('ddda') ddda: DxDropDownBoxComponent;
  @ViewChild('dddb') dddb: DxDropDownBoxComponent;
  public resource: any[];
  // 表格数据
  items: any[] = [];
  // 选中行数据
  selectedRow = null;
  isRowSelected = false;
  // 操作
  operation: string;
  // 提交数据
  // 任务名称
  jobName: string;
  // 任务描述
  description: string;
  // 邮件地址列表
  emailAddressesItem: any[] = [];
  // 选中地址
  emailAddressesSelected: any[];
  // cron表达式列表
  cronItem: any[] = [];
  // cron表达式
  cronSelected: any;
  //任务组名
  public jobGroupName: any;
  //任务类名列表
  public classItem: any[] = [];
  //任务类名
  public jobClassName: any;
  // 数据查询时间范围列表
  dateItem: any[] = [];
  // 数据查询时间范围值
  dateSelected: any;
  
  public format = 'YYYYMMDD';

  constructor(private commServices: CommService) {
  }
  // 组件初始化
  ngOnInit() {
    this.subAreaItems = this.commServices.getSubAreas();
    // 时间组件
    //this.commServices.initDatePicker($('#DateTimeRange'), 'YYYY-MM-DD HH:mm');
    // 邮件地址列表
    this.getEmailAddressesList();
    // cron表达式列表
    this.cronItem = [
      //{ 'key': '10秒执行一次', value: '0/10 * * * * ?' },
      { 'key': '2分钟执行一次', value: '0 0/2 * * * ?' },
      { 'key': '每天执行一次', value: '0 15 8 * * ?' },
      { 'key': '每周执行一次', value: '0 15 8 ? * MON' },
      { 'key': '每月执行一次', value: '0 15 8 1 * ? *' }
    ];
    this.classItem = [
      { 'key': 'FTA', value: 'com.sgm.pt.pmc.report.task.FTAEmail'}, 
      { 'key': 'WorkingPace', value: 'com.sgm.pt.pmc.report.task.WorkingSpaceEmail'},
      { 'key': 'excel', value: 'com.sgm.pt.pmc.report.task.OeeReportEmailTask'},
    ];

    this.dateItem = [
      { 'key': '前一天数据', value: moment().subtract(1, 'days').format(this.format) + ' - ' + moment().format(this.format) },
      { 'key': '上周数据', value: moment().subtract(1, 'week').startOf('isoWeek').format(this.format) + ' - ' + moment().startOf('isoWeek').format(this.format) },
      { 'key': '本周数据', value: moment().startOf('isoWeek').format(this.format) + ' - ' + moment().format(this.format) },
      { 'key': '上月数据', value: moment().subtract(1, 'months').startOf('month').format(this.format) + ' - ' + moment().startOf('month').format(this.format) },
      { 'key': '本月数据', value: moment().startOf('month').format(this.format) + ' - ' + moment().format(this.format) }
    ]
    // 初始化
    this.initData();
    // 获取初始化查询数据
    this.getReportData();
  }
  /**获取TimeRange的值*/
  getTime(id: any): String {
    const timerange: String = $('#' + id).val();
    return timerange;
  }
  /**
   * 获取表格数据
   */
  getReportData(): void {
    const queryModel: QueryModel = new QueryModel();
    // queryModel.querySubAreaIds = [this.subAareSelected.subArea];
    this.commServices
      .getList(queryModel, ReportUrls.EmailTaskConfigList)
      .subscribe(model => {
        if (model.resultCode === 200) {
          this.items = model.data.map(a => this.formatGridData(a));
        } else {
          console.log(model.resultCode + ',' + model.resultMessage);
        }
      });
  }

  // 格式化后台数据
  formatGridData(data) {
    // 状态字段转化
    if (data.status === 1) {
      data.statusText = '正常';
    } else {
      data.statusText = '暂停';
    }
    // 参数字段拆分
    const param = JSON.parse(data.parameter);
    data.subAreas = param.subAreas;
    data.emailAddresses = param.emailAddresses;
    data.timeRange = param.timeRange;
    data.startTime = data.timeRange.split('-')[0];
    data.endTime = data.timeRange.split('-')[1];
    return data;
  }
  getEmailAddressesList() {
    this.commServices
      .getList({}, ReportUrls.AllUser)
      .subscribe(model => {
          if (model.resultCode === 200) {
            this.emailAddressesItem = model.data.allUser;
          } else {
            console.log(model.resultCode + ',' + model.resultMessage);
          }
      });
  }
  // 行点击事件
  rowClick(event) {
    this.selectedRow = event.data;
    this.isRowSelected = true;
    // console.log('selectedRow', this.selectedRow);
  }
  // 格式化表单数据
  initData() {
    this.jobName = '';
    this.description = '';
    this.jobClassName = this.classItem[0];
    this.jobGroupName = GlobalDataManager.getProjectSelected().projectName;
    this.emailAddressesSelected = [];
    this.cronSelected = this.cronItem[1];
    this.dateSelected = this.dateItem[0];
    this.subAreaSelected = [];
  }
  // 清空区域选择
  clearSubAreaSelected() {
    this.subAreaSelected = [];
  }
  // 确定区域选择
  subAreaSelectedOk() {
    this.ddda.instance.close();
  }
  // 清空区域选择
  clearEmailAddressesSelected() {
    this.emailAddressesSelected = [];
  }
  // 确定区域选择
  emailAddressesSelectedOk() {
    this.dddb.instance.close();
  }
  // 添加定时任务
  addData() {
    this.operation = '添加';
    this.initData();
  }
  // 编辑定时任务
  editData() {
    this.operation = '编辑';
    const data = Object.assign({}, this.selectedRow);
    if (this.selectedRow != null) {
      this.jobName = data.jobName;
      this.description = data.description;
      this.jobClassName = this.classItem.find(a => a.value === data.class);
      this.jobGroupName = data.jobGroupName;
      this.cronSelected = this.cronItem.find(a => a.value === data.cron);
      this.emailAddressesSelected = this.emailAddressesItem.filter(a => data.emailAddresses.indexOf(a.email) >= 0);
      this.subAreaSelected = this.subAreaItems.filter(a => data.subAreas.indexOf(a.subArea) >= 0);
      //$('#DateTimeRange').val(data.startTime + ' - ' + data.endTime);
      this.dateSelected = this.dateItem.find(a => a.value === data.date);
    }
  }
  // 暂停定时任务
  pauseData() {
    if (!this.selectedRow) {
      alert('未选中行数据');
      return;
    }
    this.commServices
      .getList(this.selectedRow, ReportUrls.EmailTaskConfigPause)
      .subscribe(model => {
        if (model.resultCode === 200) {
          this.getReportData();
        } else {
          console.log(model.resultCode + ',' + model.resultMessage);
        }
      });
  }
  // 恢复定时任务
  resumeData() {
    if (!this.selectedRow) {
      alert('未选中行数据');
      return;
    }
    this.commServices
      .getList(this.selectedRow, ReportUrls.EmailTaskConfigResume)
      .subscribe(model => {
        if (model.resultCode === 200) {
          this.getReportData();
        } else {
          console.log(model.resultCode + ',' + model.resultMessage);
        }
      });
  }
  // 删除定时任务
  deleteData() {
    if (!this.selectedRow) {
      alert('未选中行数据');
      return;
    }
    this.commServices
      .getList(this.selectedRow, ReportUrls.EmailTaskConfigDelete)
      .subscribe(model => {
        if (model.resultCode === 200) {
          this.getReportData();
        } else {
          console.log(model.resultCode + ',' + model.resultMessage);
        }
      });
  }
  // 提交数据
  submitData() {
    // this.subAreaSelected.map(sub => {
    //   this.resource = this.commServices.getTVResourceBySubArea(sub.subArea).map(e => e.resource);
    // });
    const param = {
      emailAddresses: this.emailAddressesSelected.map(e => e.email),
      subAreas: this.subAreaSelected.map(e => e.subArea),
      // resources: this.resource,
      //timeRange: this.getTime('DateTimeRange')
      timeRange: this.dateSelected.value
    };
    console.log(param);
    debugger
    if (this.operation === '添加') {
      const data = {
        jobName: this.jobName,
        description: this.description,
        jobGroupName: this.jobGroupName,
        jobClassName: this.jobClassName.value,
        cron: this.cronSelected.value,
        parameter: JSON.stringify(param)
      };
      this.commServices
      .getList(data, ReportUrls.EmailTaskConfigAdd)
      .subscribe(model => {
        if (model.resultCode === 200) {
          this.getReportData();
          this.initData();
        } else {
          console.log(model.resultCode + ',' + model.resultMessage);
        }
      });
    } else {
      const data = Object.assign({}, this.selectedRow);
      data.description = this.description;
      data.cron = this.cronSelected.value;
      data.parameter = JSON.stringify(param);
      this.commServices
      .getList(data, ReportUrls.EmailTaskConfigUpdate)
      .subscribe(model => {
        if (model.resultCode === 200) {
          this.getReportData();
          this.initData();
        } else {
          console.log(model.resultCode + ',' + model.resultMessage);
        }
      });
    }
  }
}
